<template>
  <div v-loading.lock="loading" class="base-content">
    <div class="basic-info">
      <el-form
        ref="queryForm"
        :inline="true"
        :model="queryForm"
        label-width="120px"
      >
        <el-form-item :label="dataList.TaskNumber" prop="num">
          <el-input
            v-model="queryForm.num"
            :placeholder="dataList.TaskNumber"
          />
        </el-form-item>
        <el-form-item :label="dataList.Device" prop="deviceNum">
          <el-input
            v-model="queryForm.deviceNum"
            :placeholder="dataList.EquipNumberOrName"
          />
        </el-form-item>
        <el-form-item :label="dataList.DeviceClassifyId" prop="classifyId">
          <div style="width: 200px">
            <DeviceCategory v-model="queryForm.classifyId" :is-all="true" />
          </div>
        </el-form-item>
        <el-form-item :label="dataList.AssPlanNumber" prop="maintenanceNum">
          <el-input
            v-model="queryForm.maintenanceNum"
            :placeholder="dataList.AssPlanNumber"
          />
        </el-form-item>
        <el-form-item :label="dataList.MaintainType" prop="type">
          <div style="width: 200px">
            <el-select
              v-model="queryForm.type"
              :placeholder="dataList.Placeholder"
            >
              <el-option
                v-for="item in maintainTypeOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </div>
        </el-form-item>
        <el-form-item :label="dataList.Status" prop="status">
          <div style="width: 200px">
            <el-select
              v-model="queryForm.status"
              :placeholder="dataList.Placeholder"
            >
              <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </div>
        </el-form-item>

        <el-form-item
          :label="dataList.MaintenancePersonnel"
          prop="maintenancePersonName"
        >
          <el-input
            v-model="queryForm.maintenancePersonName"
            :placeholder="dataList.MaintenancePersonnel"
          />
        </el-form-item>
        <el-form-item :label="dataList.MainTime" prop="maintenanceDate">
          <el-date-picker
            v-model="queryForm.maintenanceDate"
            type="daterange"
            :range-separator="dataList.To"
            :start-placeholder="dataList.StartDate"
            :end-placeholder="dataList.EndDate"
          >
          </el-date-picker>
        </el-form-item>
      </el-form>

      <div class="base-content-operate">
        <el-button type="primary" @click="onQuery">{{ btn.Query }}</el-button>
        <el-button @click="cancelForm">{{ btn.Reset }}</el-button>
        <el-button icon="el-icon-plus" type="primary" @click="onNew">{{
          btn.Add
        }}</el-button>
        <el-button type="primary" @click="Export">{{ btn.Export }}</el-button>
        <el-button icon="el-icon-plus" type="primary" @click="editAccendant">{{
          btn.ModifyMainPerson
        }}</el-button>
      </div>

      <el-table
        ref="DeviceMaintenanceTaskList"
        :data="list"
        element-loading-text="Loading"
        fit
        highlight-current-row
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55"> </el-table-column>
        <el-table-column :label="dataList.TaskNumber">
          <template slot-scope="scope">
            <el-link type="primary" @click="toView(scope.row)">
              {{ scope.row.num }}</el-link
            >
          </template>
        </el-table-column>
        <el-table-column :label="dataList.DeviceNumber">
          <template slot-scope="scope">
            {{ scope.row.device !== null ? scope.row.device.num : "" }}
          </template>
        </el-table-column>
        <el-table-column
          :label="
            $i18n.locale === 'en' ? dataList.DeviceEName : dataList.DeviceName
          "
        >
          <template slot-scope="scope">
            {{ scope.row.device !== null ? scope.row.device.name : "" }}
          </template>
        </el-table-column>
        <el-table-column :label="dataList.ScheduledMaintenanceTime">
          <template slot-scope="scope">
            {{ formatTime(scope.row.planDate) }}
          </template>
        </el-table-column>
        <el-table-column :label="dataList.Type">
          <template slot-scope="scope">
            {{ scope.row.typeName }}
          </template>
        </el-table-column>
        <el-table-column :label="dataList.MaintenanceTask">
          <template slot-scope="scope">
            {{ scope.row.project }}
          </template>
        </el-table-column>
        <el-table-column :label="dataList.AssPlanNumber">
          <template slot-scope="scope">
            {{
              scope.row.deviceMaintenance === null
                ? ""
                : scope.row.deviceMaintenance.num
            }}
          </template>
        </el-table-column>
        <el-table-column :label="dataList.Status">
          <template slot-scope="scope">
            {{ scope.row.statusName }}
          </template>
        </el-table-column>
        <el-table-column :label="dataList.MaintenancePersonnel">
          <template slot-scope="scope">
            {{ scope.row.maintenanceUser.name }}
          </template>
        </el-table-column>
        <el-table-column :label="dataList.MainTime">
          <template slot-scope="scope">
            {{ formatTime(scope.row.maintenanceDate) }}
          </template>
        </el-table-column>
        <el-table-column :label="dataList.Operation">
          <template slot-scope="scope">
            <div class="base-table-operation">
              <el-link
                v-if="scope.row.status === 10"
                size="mini"
                type="primary"
                @click="handleEdit(scope.row)"
                >{{ btn.Process }}</el-link
              >
              <el-link
                v-if="scope.row.status === 10 && scope.row.type === 20"
                size="mini"
                type="danger"
                @click="handleDelete(scope.row)"
                >{{ btn.Nullify }}</el-link
              >
            </div>
          </template>
        </el-table-column>
      </el-table>

      <BasePagination
        :total="pagination.total"
        :current-page="pagination.pageIndex"
        :page-count="pagination.total"
        @changePage="changePage"
        @sizeChange="sizeChange"
      />
    </div>

    <el-dialog
      class="base-dialog system-user-dialog"
      :custom-class="'panna-dialog_small'"
      :append-to-body="true"
      :title="dataList.ModifyMainPerson"
      align="center"
      :close-on-click-modal="false"
      :visible.sync="editAccendantVisible"
    >
      <el-form
        ref="formData"
        label-width="100px"
        :model="formData"
        :rules="formDataRules"
        status-icon
      >
        <el-form-item
          :label="dataList.MaintenancePersonnel"
          :label-width="formLabelWidth"
          prop="maintenancePersonId"
          :error="errorMsg.maintenancePersonId"
        >
          <UserDropDownList
            :value="formData.maintenancePersonId"
            @input="borrowPersonChange"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" align="center">
        <el-button type="primary" @click="onSubmit('formData')">{{
          btn.Save
        }}</el-button>
        <el-button @click="cancel">{{ btn.Cancel }}</el-button>
      </div>
    </el-dialog>

    <DeviceMaintenanceTaskAddDialog
      v-if="dialogFormVisible"
      ref="DeviceBorrowAddDialog"
      :dialog-form-visible.sync="dialogFormVisible"
    />
    <DeviceMaintenanceTaskDisposeDialog
      v-if="eviceMaintenanceTaskDisposeVisible"
      :id.sync="id"
      ref="DeviceMaintenanceTaskDisposeDialog"
      :dialog-form-visible.sync="eviceMaintenanceTaskDisposeVisible"
    />
    <DeviceMaintenanceTaskDisposeViewDialog
      v-if="dialogFormViewVisible"
      :id.sync="id"
      ref="DeviceMaintenanceTaskDisposeViewDialog"
      :dialog-form-visible.sync="dialogFormViewVisible"
    />
  </div>
</template>

<script>
import DeviceCategory from "../../../components/DeviceCategory.vue";
import {
  getList,
  updateMaintenancePerson,
  update,
} from "../../../api/DeviceMaintenanceTask";
import DeviceMaintenanceTaskAddDialog from "./DeviceMaintenanceTaskAddDialog.vue";
import UserDropDownList from "../../../components/UserDropDownList.vue";
import DeviceMaintenanceTaskDisposeDialog from "./DeviceMaintenanceTaskDisposeDialog.vue";
import DeviceMaintenanceTaskDisposeViewDialog from "./DeviceMaintenanceTaskDisposeViewDialog.vue";
import { maintenanceTaskStatus, maintainType } from "../../../utils/const";
import { formatTimeMin, formatTimeMax, formatTime } from "../../../utils/time";
import { export_json_to_excel } from "@/vendor/Export2Excel";

export default {
  name: "DeviceMaintenanceTaskList",
  components: {
    DeviceMaintenanceTaskAddDialog,
    UserDropDownList,
    DeviceMaintenanceTaskDisposeDialog,
    DeviceMaintenanceTaskDisposeViewDialog,
    DeviceCategory,
  },
  data() {
    return {
      id: 0,
      // tHeader: [
      //   "任务编号",
      //   "设备编号",
      //   "设备名称",
      //   "设备分类",
      //   "责任人",
      //   "责任部门",
      //   "维保项目",
      //   "维护人",
      //   "维护时间",
      //   "维护后设备状态",
      //   "备注",
      // ],
      filterVal: [
        "num",
        "deviceNum",
        "deviceName",
        "classifyName",
        "personResponsibleName",
        "departName",
        "project",
        "maintenanceUser",
        "maintenanceDate",
        "maintenanceStatusName",
        "remark",
      ],
      dialogFormViewVisible: false,
      maintainTypeOptions: maintainType,
      options: maintenanceTaskStatus,
      eviceMaintenanceTaskDisposeVisible: false,
      // 维护人名字
      maintenancePersonName: "",
      editAccendantVisible: false,
      loading: true,
      list: [],
      tableData: [],
      formData: {
        maintenancePersonId: null,
        deviceMaintenanceTaskIdList: [],
      },
      errorMsg: {
        maintenancePersonId: null,
      },
      formLabelWidth: "100px",
      formDataRules: {
        maintenancePersonId: [
          {
            required: true,
            trigger: "blur",
            validator: this.Helper.validateFunction,
          },
        ],
      },
      queryForm: {
        num: "",
        endTime: null,
        stateTime: null,
        classifyId: "-1",
        deviceNum: "",
        maintenanceDate: [],
        maintenanceNum: "",
        status: -1,
        type: -1,
        maintenancePersonName: "",
        departId: sessionStorage.getItem("currentDepartmentId"),
      },
      dialogFormVisible: false,
      pagination: {
        pageIndex: 1,
        pageSize: 10,
        total: 0,
      },
    };
  },
  computed: {
    btn() {
      return this.$t("ModuleDevice.buttons");
    },
    dataList() {
      return this.$t("ModuleDevice.Device");
    },
  },
  created() {
    this.getList();
  },
  methods: {
    formatTime,
    export_json_to_excel,
    formatJson(filterVal, jsonData) {
      return jsonData.map((v) =>
        filterVal.map((j) => {
          return v[j];
        })
      );
    },
    toView(row) {
      this.id = row.id;
      this.dialogFormViewVisible = true;
    },
    borrowPersonChange(val) {
      this.formData.maintenancePersonId = val;
    },
    cancel() {
      this.getList();
      this.editAccendantVisible = false;
    },
    // 修改维护人
    onSubmit() {
      this.$refs.formData.validate((valid) => {
        if (valid) {
          // 获取选中的行
          var objList = [];
          var rows = this.$refs.DeviceMaintenanceTaskList.selection;
          rows.map((item) => {
            var obj = {};
            obj.maintenancePersonId = this.formData.maintenancePersonId;
            obj.id = item.id;
            objList.push(obj);
          });
          updateMaintenancePerson(objList)
            .then((res) => {
              this.cancel();
            })
            .catch((res) => {});
        }
      });
    },
    // 维护人
    editAccendant() {
      this.formData.maintenancePersonId = null;
      if (this.tableData === null || this.tableData.length === 0) {
        this.$message.warning(
          `${this.$i18n.t("ModuleDevice.Message.NoDataSelect")}!`
        );
        return false;
      }
      this.editAccendantVisible = true;
    },
    handleSelectionChange(val) {
      this.tableData = val;
    },
    // 导出
    Export() {
      var datas = [];
      this.queryForm.departId = sessionStorage.getItem("currentDepartmentId");
      getList(this.queryForm, { pageIndex: 1, pageSize: 100000 }).then(
        (res) => {
          for (let i = 0; i < res.data.dataList.length; i++) {
            var data = res.data.dataList[i];
            datas.push({
              num: data.num,
              deviceNum: data.device == null ? "" : data.device.num,
              deviceName: data.device == null ? "" : data.device.name,
              classifyName: data.device == null ? "" : data.device.classifyName,
              personResponsibleName:
                data.device == null ? "" : data.device.personResponsibleName,
              departName: data.device == null ? "" : data.device.departName,
              project: data.project,
              maintenanceUser: data.maintenanceUser.name,
              maintenanceDate: this.formatTime(data.maintenanceDate),
              maintenanceStatusName: data.maintenanceStatusName,
              remark: data.remark,
            });
          }
          var data1 = this.formatJson(this.filterVal, datas);
          const tHeader = [
            this.dataList.TaskNumber,
            this.dataList.DeviceNumber,
            this.dataList.DeviceName,
            this.dataList.DeviceClassifyId,
            this.dataList.DevicePersonResponsibleId,
            this.dataList.Devicedepart,
            this.dataList.MaintenanceTask,
            this.dataList.MaintenancePersonnel,
            this.dataList.MainTime,
            this.dataList.EquipStatusAfterMain,
            this.dataList.Deviceremark,
          ];
          export_json_to_excel({
            header: tHeader, // 表头
            data: data1, // 数据
            filename: this.dataList.MaintainTask, // 导出文件名
            autoWidth: true, // 导出宽度自动
            bookType: "xlsx", // 导出后缀
          });
        }
      );
    },
    changePage(val) {
      this.pagination.pageIndex = val;
      this.getList();
    },
    sizeChange(val) {
      this.pagination.pageIndex = 1;
      this.pagination.pageSize = val;
      this.getList();
    },
    cancelForm() {
      this.$refs.queryForm.resetFields();
      this.pagination.pageIndex = 1;
      this.getList();
    },
    getList() {
      this.loading = true;
      this.queryForm.stateTime = formatTimeMin(
        this.queryForm.maintenanceDate[0]
          ? this.queryForm.maintenanceDate[0]
          : null
      );
      this.queryForm.endTime = formatTimeMax(
        this.queryForm.maintenanceDate[1]
          ? this.queryForm.maintenanceDate[1]
          : null
      );
      // this.queryForm.departId =  sessionStorage.getItem("currentDepartmentId");
      getList(this.queryForm, this.pagination)
        .then((res) => {
          this.list = res.data.dataList ? res.data.dataList : [];
          this.pagination.total = res.data.total;
          this.loading = false;
        })
        .catch(() => {
          this.loading = false;
        });
    },
    onNew() {
      this.dialogFormVisible = true;
    },
    handleDelete(rowData) {
      this.$confirm(
        this.$t("ModuleDevice.Message.ConfirmNullify"),
        this.$t("ModuleDevice.buttons.Tips"),
        {
          confirmButtonText: this.$t("ModuleDevice.buttons.Confirm"),
          cancelButtonText: this.$t("ModuleDevice.buttons.Cancel"),
          type: "warning",
          center: true,
        }
      )
        .then(() => {
          rowData.status = 70;
          rowData.statusName = this.dataList.Invalid;
          rowData.deviceId = rowData.device.id;
          update(rowData)
            .then((res) => {})
            .catch((res) => {});
        })
        .catch(() => {});
    },
    handleEdit(row) {
      this.id = row.id;
      this.eviceMaintenanceTaskDisposeVisible = true;
    },
    onQuery() {
      this.pagination.pageIndex = 1;
      this.getList();
    },
  },
};
</script>
